package com.flowcanto.gs1demo.server;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class FileListCreator extends javax.servlet.http.HttpServlet {
	Webserver server;

	// Start the thread in the constructor
	public FileListCreator( Webserver server ) {
		this.server = server;
	}

	@Override
	protected void doGet( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException {
		/*
		 * At this point we must check the dir "output" for files and create a
		 * nice list of that.
		 */

		File outputDir = new File( server.applicationDirectory() + "output" );

		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			Document doc = db.newDocument();
			Element files = doc.createElement( "files" );
			doc.appendChild( files );
			
			String[] sFiles = outputDir.list();
			for( String name : sFiles ) {
				if( !new File( server.applicationDirectory() + "output/" + name )
						.isDirectory() ) {
					Element file = doc.createElement( "file" );
					
					if( name.contains( "despatchadvice" ) ) {
						file.setAttribute( "schema", "FoodserviceDespatchAdvice.xsd" );
					} else if( name.contains( "invoice" ) ) {
						file.setAttribute( "schema", "FoodserviceInvoice.xsd" );
					} else {
						file.setAttribute( "schema", "unknown schema for: " + name );
					}
					
					file.setAttribute( "src", name );
					
					files.appendChild( file );
				}
			}
			
			response.setContentType( "text/xml;charset=utf-8" );
			OutputStream os = response.getOutputStream();
			
			Transformer t = TransformerFactory.newInstance().newTransformer();
			t.transform( new DOMSource( doc ), new StreamResult( os ) );
			
		} catch( Exception e ) {
			e.printStackTrace();
		}
	}
}
